<?php

namespace app\console\controller;

use think\facade\Session;
use think\facade\Cache;
use think\facade\Url;
use app\console\model\Admin as AdminModel;
use app\console\validate\Admin as AdminValidate;
use app\common\model\DomainReport;
use app\console\controller\Base;

/**
 * 首页controller
 * */
class Index extends Base
{
    public function __construct()
    {
        parent::__construct();
        $this->assign('active', 'console');
        $this->assign('topbar', '');
    }

    /**
     * 首页统计信息
     * */
    public function index()
    {
        $today_report_res = $this->domain_report();
        if (!$today_report_res) {
            $today_report_res['eye_pc_num'] = 0;
            $today_report_res['eye_m_num'] = 0;
        }

        $this->assign([
            'today_report_res' => $today_report_res,
        ]);
        return $this->fetch();
    }

    /**
     *站点浏览量统计
     * */
    protected function domain_report()
    {
        $today_start = strtotime(date('Ymd'));
        $today_report_res = DomainReport::get(['day_start_time' => $today_start]);
        return $today_report_res;
    }

    /**
     * 管理员修改密码
     * */
    public function repass()
    {
        if ($this->request->isAjax()) {
            if (ADMIN_ID == 0) {
                $this->success('您无需修改密码哦(#^.^#)', Url::build('console/index/index'));
                exit;
            }
            $data = $this->request->post();
            $check = (new AdminValidate())->scene('edit_password')->gocheck($data);
            if ($check['code'] == 0) $this->error($check['msg']);
            $result = AdminModel::repass(ADMIN_ID, $data['old_pass'], $data['new_pass']);
            if ($result['code']) {
                $this->success($result['msg'], Url::build('console/index/index'));
            }
            $this->error($result['msg']);
            exit;
        }
        $this->assign('topbar', ['修改密码']);
        return $this->fetch();
    }


    /**
     * 清除缓存
     * */
    public function clear_cache()
    {
        if ($this->request->isAjax()) {
            Cache::clear();
            $this->success('清除成功');
            exit;
        }
    }

    /**
     * 退出
     * */
    public function logout()
    {
        Session::clear('console');
        $this->redirect('console/index/index');
    }

}
